"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
  xxhelper(PB能力扩展工具集)
  create:20240421 重构
  by:xiaox
  
  注意事项:
  1、参数要保证字符串不包含空格,防止误判为多个参数
  2、不包含 & 符号,这个是CMD 的保留字   
  3、powershell 会忽略$,请用命令行  
 
  一、运行方法
  xxhelper app=工具名称$key1=value1$key2=value2$...    

  二、运行状态及返回信息查看
  1、D:/xxhelper.log 文件，会输出工具运行的一些反馈、及错误信息。
  2、部分工具,可以传入PB接收反馈信息的窗口名称,工具以sendmessage
  方式给窗口发送消息。
  
  打包 pyinstaller xxhelper.py -F -w
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

import requests
import sys
import logging
import os
import win32api
import json

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models
  
# args参数解析成DICT
def _getArgs(argstring):    
  lis = argstring.split("$")
  lis = [x for x in lis if "=" in x]
  args = {}
  for x in lis:
    args[x.split("=")[0]] = x.split("=")[1]
  return args

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
  腾讯手机短信接口
  xxhelper.exe app=sms$to=18627472125$tempId=1389962$paramLis=1,2,3,4$hwnd=2690938    
  python xxhelper.py app=sms$to=18627472125$tempId=1389962$paramLis=1,2,3,4$hwnd=2690938
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

def sms(args):
  to = args["to"]
  tempId = args["tempId"]
  paramLis = args["paramLis"]
  hwnd = int(args["hwnd"])
  
  try:
    cred = credential.Credential("AKIDymLfqseCXceQwB9qGQJvFJQHrACxRebG", "QZS4PSEjywd3C4fz3qLdfQt51h9J1Xnn")
    httpProfile = HttpProfile()
    httpProfile.endpoint = "sms.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

    req = models.SendSmsRequest()
    params = {
      "PhoneNumberSet": to.split(","),
      "SmsSdkAppId": "1400671884",
      "SignName": "蓝华软件",
      "TemplateId": tempId,
      "TemplateParamSet":paramLis.split(",")
    }
    req.from_json_string(json.dumps(params))

    resp = client.SendSms(req)
    # print(resp.to_json_string())
    
    win32api.PostMessage(hwnd, 1600, 1, 1)

  except TencentCloudSDKException as err:
    win32api.PostMessage(hwnd, 1600, 1, 0)
      # print(err)

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
上传图片到http服务器
功能说明:通过api/Login/UpLoadImg接口上传图片文件
参数说明:   
app:upimg 
host:接口主机地址 例:http://0.0.0.0/
imgtype :图片类型 
imgid:图片的编号 服务器保存图片格式为:类型前缀+编号+扩展名。
file:待传图片的文件名 例:abc.jpg
path:待传图片的路径 例:d:/test/abc.jpg
imgtype:图片前缀  

调用示例:
python xxhelper.py app=upimg$host=http://139.9.176.16/$imgid=abc$file=abc.jpg$path=d:/abc.png$imgtype=product$hwnd=2690938
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
# 上传图片接口
def upimg(args):  
  try:
    host = args["host"]
    imgid = args["imgid"]
    file = args["file"]
    path = args["path"]
    imgtype = args["imgtype"]
    hwnd = int(args["hwnd"])
  except Exception as e:
    logging.error("获取参数失败,Err detail:")
    logging.debug(e)
    os._exit(0)

  url = f"{host}/api/Login/UpLoadImg?imgid={imgid}&imgtype={imgtype}"
  
  try:
    files = {'file': (file, open(path, 'rb'))}
    logging.info(f"\nrequest:{url}\n")
    try:
      req = requests.post(url, files=files)
      win32api.PostMessage(hwnd, 1600, 1, 1)
    except Exception as e:
      win32api.PostMessage(hwnd, 1600, 1, 0)
      logging.error("请求失败！")
      logging.error("Errs:")
      logging.error(e)
  except Exception as e:
    win32api.PostMessage(hwnd, 1600, 1, 0)       

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
lh-erp 获取dat文件
python xxhelper.py app=getdatfile$bm=eb034880387cd661ad784566821aae30$out=d:/aaa$http=satrda.lanhuasoft.com:808
xxhelper app=getdatfile$bm=eb034880387cd661ad784566821aae30$out=d:/aaa$http=satrda.lanhuasoft.com:808
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""    
def getdatfile(args):    
  # print(args)
  payload={
    'user': 'lanhua',
    'password': '',
    'pwd': '33e3185c742a79dcaa5b493e6380b7b3'
  }  
  host = args.get('http', "www.satrda.com:808")
  url = f"http://{host}/login/action"
  response = requests.request("POST", url, data=payload)
  _token = response.json()["Reason"]
 
  url = f"http://{host}/admin/auth/license.sat?num=9999999&bm={args['bm']}"  
  headers = {
    'Cookie': f'token={_token}'
  }
  response = requests.request("GET", url, headers=headers)
  response.raise_for_status()
  playFile = open(f'{args["out"]}/license.sat','wb')
  for chunk in response.iter_content(3000):
    playFile.write(chunk)
  playFile.close   


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
http下载文件
python xxhelper.py app=httpfile$target=http://kaifa.lanhuasoft.com:5380/uploads/images/product10101001.JPG$dist=d:/1234.jpg
xxhelper app=httpfile$target=http://kaifa.lanhuasoft.com:5380/uploads/images/product10101001.JPG$dist=d:/11111.jpg
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""    
def httpfile(args):    
  try:
    response = requests.request("GET", args["target"])
    response.raise_for_status()
    playFile = open(args["dist"],'wb')
    for chunk in response.iter_content(3000):
      playFile.write(chunk)
    playFile.close   
  except BaseException as e:
    logging.error(e)


# ========================================================================
# 没有携带参数运行程序
if sys.argv.__len__() < 2:  
  raise BaseException("程序运行需要携带必要参数")

# 参数没有带app
args = _getArgs(sys.argv[1])
appname = args.get("app", None).lower()
if not appname:
  raise BaseException("程序运行需要携带必要参数") 

# 没有定义 appname 对应的方法
if appname not in globals():
  raise BaseException("app名称无效")

# appname对应的对象不是可调用的，也就是说不是方法
app = globals()[appname]     
if not callable(app):  
  raise BaseException("app名称无效")

# 日志输出配置
driveLetter = "d:/" if os.path.isdir("d:/") else "c:/" 
basePath = os.path.join(driveLetter,"xxhelper_logs")
if not os.path.isdir(basePath):
  try:  
    os.makedirs(basePath)      
  except OSError as e:  
    raise BaseException("创建日志目录失败")

logging.basicConfig(
  level=logging.DEBUG,
  format="%(asctime)s [%(levelname)s] %(message)s",
  datefmt="%Y-%m-%d  %H:%M:%S",
  filename=os.path.join(basePath,appname+".log")
)

# 启动应用
app(args)